package com.scf.common.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author sunchuanfu
 */
public class RangeCheckValidator implements ConstraintValidator<RangeCheck, Object> {
    private RangeCheck rangeCheck;

    @Override
    public void initialize(RangeCheck rangeCheck) {
        this.rangeCheck = rangeCheck;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        // 注解表明为必选项 则不允许为空，否则可以为空
        if (value == null) {
            return !this.rangeCheck.required();
        }

        String[] validValues = this.rangeCheck.values();
        for (String validValue : validValues) {
            if (validValue.equals(value)) {
                return true;
            }
        }

        return false;
    }

}
